/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aviso.entity.util;

import aviso.controller.LocaleController;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author avgusti
 */
public class LocaleService {

    private String defaultBundle = "resources.Bundle";
    private String url="C:\\tmp.properties";
    private Properties properties = new Properties();
    private ResourceBundle bundle;
    private static LocaleService ref;

    private LocaleService() {
    }

    //@PostConstruct
    private void init() {
        ref = this;
        bundle = ResourceBundle.getBundle(defaultBundle);
        File f = null;
        FileInputStream is = null;
        try {
            f = new File(url);
            if (f.exists()) {
                properties.load((is = new FileInputStream(f)));
            }
        } catch (Exception ex) {
            Logger.getLogger(LocaleService.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException ex) {
                    Logger.getLogger(LocaleService.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    //@PreDestroy
    public void destroy() {
        File f = null;
        FileOutputStream os = null;
        try {
            f = new File(url);
            if (!f.exists()) {
                f.createNewFile();
            }
            os = new FileOutputStream(f);
            properties.store(os, "");

        } catch (Exception ex) {
            Logger.getLogger(LocaleController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException ex) {
                    Logger.getLogger(LocaleController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }


    }

    public static LocaleService getInstance() {
        if (ref == null) {
            ref = new LocaleService();
            ref.init();
        }
        return ref;
    }
    public static String getTranslation(String tr) {
        if (ref == null) {
            getInstance();
        }
        return ref.translate(tr);
    }
    public synchronized String translate(String tr) {
        try {
            return bundle.getString(tr);
        } catch (Exception e) {
            String resp = properties.getProperty(tr);
            if (resp != null) {
                return resp;
            }
            properties.put(tr, tr);
            return "[" + tr + "]";
        }
    }
}
